package com.zhongwang.mms.module.jiaGongStorage.service;

import com.zhongwang.mms.common.JsonResult;
import com.zhongwang.mms.gen.entity.PInventory;
import com.zhongwang.mms.gen.entity.User;
import com.zhongwang.mms.module.half.dao.PAllocationRecordDao;
import com.zhongwang.mms.module.jiaGongStorage.dao.StorageAccountQueryDao;
import com.zhongwang.mms.module.jiaGongStorage.model.*;
import com.zhongwang.mms.module.purchase.dao.PurChangeDao;
import com.zhongwang.mms.module.purchase.dao.PurPInventoryDao;
import com.zhongwang.mms.module.purchase.dao.PurWarQueryDao;
import com.zhongwang.mms.module.purchase.model.*;
import com.zhongwang.mms.module.purchase.service.PurWarOutManageService;
import com.zhongwang.mms.module.system.log.LogService;
import com.zhongwang.mms.module.system.user.UserDao;
import com.zhongwang.mms.util.ExportExcelUtils;
import com.zhongwang.mms.util.ShiroUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

/**
 * @ClassName： AllocationManageService
 * @Description： 出入库查询业务逻辑层
 * @Author： China.zh
 * @Date： 2020/4/8 10:36
 * @Version： V1.0
 **/
@Log4j2
@Service
public class StorageAccountQueryService {
    @Autowired
    private PurWarQueryDao purWarQueryDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private PAllocationRecordDao pAllocationRecordDao;
    @Autowired
    private PurPInventoryDao purPInventoryDao;
    @Autowired
    private PurChangeDao purChangeDao;
    @Autowired
    private PurWarOutManageService purWarOutManageService;
    @Autowired
    private StorageAccountQueryDao storageAccountQueryDao;
    @Autowired
    private LogService logService;
    @Value("${user.upload.path}")
    private String uploadPath;
    @Value("${spring.profiles.active}")
    private String active;

    /**
     * findPurWarList
     * 加载出入库列表以及综合查询
     *
     * @param param 查询条件
     * @return
     */
    public List<JStorageInventory> findPurWarList(JStorageInventory param) {
        if (param.getPEndDate() != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(param.getPEndDate());
            cal.add(Calendar.DAY_OF_YEAR, 1);
            param.setPEndDate(cal.getTime());
        }
        return storageAccountQueryDao.selectByParam(param);
    }

    /**
     * 出入库查询 查看明细
     *
     * @param param
     * @return
     */
    public JAccountStorage findOrderInfoByOdrId(JAccountStorageQueryModel param) {
        JAccountStorage jAccountStorage = new JAccountStorage();
        JStorage jStorage = storageAccountQueryDao.getOrderByOdrId(param.getOdrId());
        jStorage.setOdrMakePerson(userDao.findUserById(jStorage.getOdrMakePersonId()).getName());
        List<JStorageDetail> jStorageDetails = null;
        if (jStorage.getOdrType().intValue() == 1) {
            jStorageDetails = storageAccountQueryDao.getOrderInByOdrId(param.getOdrId());
        } else {
            jStorageDetails = storageAccountQueryDao.getOrderOutByOdrId(param.getOdrId());
        }
        if (jAccountStorage.getIsChangeFlag() == null) {
            jAccountStorage.setIsChangeFlag(0);
        }
        jAccountStorage.setFormData(jStorage);
        jAccountStorage.setInsertData(jStorageDetails);
        return jAccountStorage;
    }

    /**
     * @FunctionName: getChangeOrderInvCount
     * @Description: 获取已执行的和已出库库存信息，获取其数量进行相加
     * @DesignIdea: 默认认为只串一次料
     * @Author: 徐一贺
     * @CreateDate: 2020/6/29 13:32
     * @Phone: 18241927380
     * @Param:
     * @Return:
     * @Throw:
     * @Version: v 1.0.0
     */
    private Double getChangeOrderInvCount(Integer ceoUseItyId) {
        Double result = 0d;
        //获取根节点列表
        List<PChangeOrderModel> pChangeOrderModelList = purChangeDao.findPChangeOrderListByCeoNeedItyId(ceoUseItyId);
        for (PChangeOrderModel pChangeOrderModel : pChangeOrderModelList) {
            PInventoryModel pInvModel = purPInventoryDao.getInventoryByPrimaryKey(pChangeOrderModel.getCeoNeedItyId());
            result += pInvModel.getItyNum();
        }
        return result;
    }

    private Double getChangeUseOrderInvCount(Integer ceoUseItyId) {
        Double result = 0d;
        //获取根节点列表
        List<PChangeOrderModel> pChangeOrderModelList = purChangeDao.findPChangeOrderListByCeoUseItyId(ceoUseItyId);
        for (PChangeOrderModel pChangeOrderModel : pChangeOrderModelList) {
            PInventoryModel pInvModel = purPInventoryDao.getInventoryByPrimaryKey(pChangeOrderModel.getCeoUseItyId());
            result += pInvModel.getItyNum();
        }
        return result;
    }

    /**
     * @FunctionName: findAncestorChangeData
     * @Description: 根据子孙ID 获取串料历史中始祖的信息，并获取始祖信息时的库存数量
     * @DesignIdea: 使用递归获取始祖库存ID，并返回当前信息的始祖库存信息
     * @Author: 徐一贺
     * @CreateDate: 2020/6/29 9:47
     * @Phone: 18241927380
     * @Param: [ceoNeedItyId] 需求库存ID
     * @Return: [PInventoryModel]检索到的库存信息
     * @Throw:
     * @Version: v 1.0.0
     */
    private PInventoryModel findAncestorChangeData(Integer ceoNeedItyId) {
        PInventoryModel result = purPInventoryDao.getInventoryByPrimaryKey(ceoNeedItyId);
        PChangeOrderModel currentModel = new PChangeOrderModel();
        currentModel.setCeoNeedItyId(ceoNeedItyId);
        while (true) {
            if (currentModel != null) {
                currentModel = purChangeDao.getChangeCountByCeoNeedItyId(currentModel.getCeoNeedItyId());
            }
            if (currentModel != null) {
                result = purPInventoryDao.getInventoryByPrimaryKey(currentModel.getCeoUseItyId());
                currentModel = purChangeDao.getChangeCountByCeoNeedItyId(currentModel.getCeoUseItyId());
            } else {
                break;
            }
        }
        return result;
    }

    /**
     * 列表 导出
     *
     * @param param 查询条件
     * @return list
     */
    public void exportExcel(HttpServletResponse response, PurWarQueryModel param) {
        if (param.getPEndDate() != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(param.getPEndDate());
            cal.add(Calendar.DAY_OF_YEAR, 1);
            param.setPEndDate(cal.getTime());
        }
        //获取当前用户
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        //存储/读取Excel的文件夹的路径 mms文件夹下/用户账户/
        String path = uploadPath + user.getAccount() + "/";
        Subject userSubject = ShiroUtils.getSubject();
        try {
            //1.创建临时内存表名
            String tempTableName = "##" + user.getAccount() + (UUID.randomUUID().toString().replace("-", ""));
            param.setTempTableName(tempTableName);
            //2.查询出数据导入到临时表
            if (userSubject.isPermitted("purwar:amount:view")) {
                purWarQueryDao.createWarQueryTempTableByParam(param);
            } else {
                purWarQueryDao.createWarQueryTempTableByParamAndNoAmount(param);
            }
            //3.导出Excel
            boolean result = ExportExcelUtils.Export(path, "外购件库出入库综合查询.xlsx", tempTableName, response, active);
        } catch (Exception e) {
            log.debug(e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 创建要导出的Excel
     *
     * @param param 查询条件
     * @return list
     */
    public JsonResult exportExcel(JAccountStorageQueryModel param) {
        JsonResult jsonResult = new JsonResult();
        if (param.getPEndDate() != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(param.getPEndDate());
            cal.add(Calendar.DAY_OF_YEAR, 1);
            param.setPEndDate(cal.getTime());
        }
        //获取当前用户
        User user = (User) SecurityUtils.getSubject().getPrincipal();
        logService.saveLog(param.getMode() + "——导出", "用户:【" + user.getName() + "】执行导出操作！");
        //存储/读取Excel的文件夹的路径 mms文件夹下/用户账户/
        String path = uploadPath + user.getAccount() + "/";
        Subject userSubject = ShiroUtils.getSubject();
        String excelFileName = "甲供件-外购件库出入库综合查询.xlsx";
        try {
            //1.创建临时内存表名
            String tempTableName = "##" + user.getAccount() + (UUID.randomUUID().toString().replace("-", ""));
            param.setTempTableName(tempTableName);
            //2.查询出数据导入到临时表
            storageAccountQueryDao.createWarQueryTempTableByParam(param);
            //3.导出Excel
            if (ExportExcelUtils.BuildExcel(path, excelFileName, tempTableName, active, true)) {
                jsonResult.setData(excelFileName);
                jsonResult.setType(JsonResult.ResultType.SUCCESS);
            } else {
                jsonResult.setType(JsonResult.ResultType.ERROR);
            }
        } catch (Exception e) {
            log.debug(e.getMessage());
            e.printStackTrace();
            jsonResult.setType(JsonResult.ResultType.ERROR);
        }
        return jsonResult;
    }
}
